import * as API_Address from '../../../api/address'
import * as API_Trade from '../../../api/trade'
import { Foundation, RegExp } from '../../../ui-utils/index'
let util = require('../../../utils/util.js')

Page({
  data: {
    addr_id: 0,
    finished: false,
    from: '', // 页面涞源
    addressList: [] // 地址列表
  },
  //设为默认地址
  setDefault: util.throttle(function(e) {
    let { addr } = e.currentTarget.dataset;
    if (addr.def_addr === 1) {
      return;
    };
    const addr_id = addr.addr_id;
    API_Address.setDefaultAddress(addr_id).then(() => {
      this.getAddressList();
    });
  }),
  //删除地址
  deteleAddress(e){
    let that = this;
    let _id = e.currentTarget.dataset.addr_id;
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      confirmColor: '#f42424',
      success: function (res) {
        if (res.confirm) {
          API_Address.deleteAddress(_id).then(() => {
            wx.showToast({title: '删除成功'})
            that.getAddressList()
          });
        };
      }
    });
  },
  //编辑地址
  selectAddress: util.throttle(function(e) {
    let addr_id = e.currentTarget.dataset.addr_id
    wx.navigateTo({
      url: '/pages/ucenter/addressAdd/addressAdd?addr_id='+ addr_id
    })
  }),
  //添加新地址
  addAddress: util.throttle(function(e){
    wx.navigateTo({
      url: '/pages/ucenter/addressAdd/addressAdd'
    })
  }),
  // 选择使用地址
  handleselectedaddr(e) {
    const address = e.currentTarget.dataset.address
    if (this.data.from === 'checkout') {
      API_Trade.setAddressId(address.addr_id).then(() => {
        wx.navigateBack({ delta: 1 })
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { // 设置页面来源
    this.setData({ from: options.from || '' })
  },
  onShow() { // 获取地址列表
    this.getAddressList()
  },
  getAddressList(){
    API_Address.getAddressList().then((response)=>{
      response.forEach(key => {
        key.mobile = Foundation.secrecyMobile(key.mobile)
      })
      this.setData({
        addressList:response,
        finished:true
      })
    })
  }
})